<?php

namespace app\api\controller;

use app\api\model\ConfigAlipay;
use app\api\model\OrderCommon;
use app\api\model\Topup;
use think\Request;
use think\Db;
use Yansongda\Pay\Pay;

class Alipaywap extends Common
{
    protected $config;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        $config = ConfigAlipay::get(['types' => 1, 'is_select' => 1]);

        $this->config = [
            'alipay' => [
                'app_id' => $config['appid'],
                'notify_url' => url('api/Alipaywap/notify', '', '', true),
                'ali_public_key' => $config['public_key'],
                'private_key' => $config['private_key'],
            ],
        ];
    }

    public function index($order_sn)
    {
        $state = 0;

        # 充值
        $data = Topup::get(['numbers' => $order_sn, 'state' => 0]);

        if ($data) {
            $state = 1;
            $total_amount = $data['price'];
        }

        if (!$state) {
            $data = OrderCommon::get(['number' => $order_sn, 'status' => 0]);

            if ($data) {
                $state = 1;
                $total_amount = $data['money'];
            }
        }

        if (!$state) {
            return $this->miss('订单不存在');
        }

        $form = $this->tradeAppPay($order_sn, $total_amount);

        $this->assign('form', $form);

        return $this->fetch();
    }

    public function tradeAppPay($order_sn)
    {
        $result = $this->check($order_sn);

        if ($result['code'] != 200) {
            return $this->miss($result['msg']);
        }

        $total_amount = $result['data']['total_amount'];

        $config_biz = [
            'out_trade_no' => $order_sn,
            'total_amount' => sprintf("%.2f", $total_amount),
            'subject' => '账户充值',
        ];

        $pay = new Pay($this->config);

        $result = $pay->driver('alipay')->gateway('wap')->pay($config_biz);

        return $this->pass(['url' => $result]);
    }

    private function check($out_trade_no)
    {
        $state = 0;

        $data = (new Topup)->master()->where(['numbers' => $out_trade_no, 'state' => 0])->find();

        if ($data) {
            $state = 1;
            $money = $data['price'];
            Topup::update(['id' => $data['id'], 'type' => 1]);
        }

        if (!$state) {
            $data = (new OrderCommon)->master()->where(['number' => $out_trade_no, 'status' => 0])->find();

            if ($data) {
                $state = 1;
                $money = $data['money'];
                OrderCommon::update(['id' => $data['id'], 'pays' => 2]);
            }
        }
        if (!$state) {
            $data = Db::name('mall_order')->master()->where(['number' => $out_trade_no, 'status' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['money'];
            }
        }
        
        if (!$state) {
            $data = Db::name('order_of_service')->master()->where(['number' => $out_trade_no, 'paystate' => 0, 'state' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['price'];
            }
        }
        
        if (!$state) {
            $data = Db::name('user_flag')->master()->where(['number' => $out_trade_no, 'paystate' => 0, 'status' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['price'];
            }
        }

        if (!$state) {
            $data = Db::name('user_address_red_packet')->master()->where(['number' => $out_trade_no, 'type' => 1, 'paystate' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['totalprice'];
            }
        }

        if (!$state) {
            $data = Db::name('order_of_addressgood')->master()->where(['number' => $out_trade_no, 'status' => 0, 'paystate' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['price'];
            }
        }
        
        if (!$state) {
            $data = Db::name('activity_join')->master()->where(['number' => $out_trade_no, 'paystate' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['price'];
            }
        }

        if (!$state) {
            return ['code' => 400, 'msg' => '订单不存在'];
        } else {
            return ['code' => 200, 'data' => ['total_amount' => $money]];
        }
    }

    public function returnurl(Request $request)
    {
        $pay = new Pay($this->config);

        return $pay->driver('alipay')->gateway('wap')->verify($request->param());
    }

    public function notify(Request $request)
    {
        $pay = new Pay($this->config);
        $verify = $pay->driver('alipay')->gateway('wap')->verify($request->param());

        if ($verify) {
            if (in_array($verify['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
                OrderCommon::notify($verify['out_trade_no'], $verify);
            } else {
                exit('fail');
            }
        } else {
            exit('fail');
        }
        exit('success');
    }
}
